import os

class FileManager(object):

    def __init__(self, num_runlevels):
        self.num_runlevels = num_runlevels
        self.files = []
        self.fullPaths = {}
        
        for _ in range(0, self.num_runlevels):
            # (slownik_stop, slownik_start)
            # slownik: sciezka do pliku w init.d  -> numer porzadkowy
            self.files.append(({}, {}))
        self.load()

    def load(self):
        for i in range(0, self.num_runlevels):
            rc_path = '/etc/rc' + str(i) + '.d'
            filenames = os.listdir(rc_path)
            stopDict, startDict = self.files[i]
            
            for filename in filenames:
                shortname = filename[3:]
                numstr = filename[1:3]
                
                if filename[0] == 'K':
                    # wrzuc go do slownika stopu
                    stopDict[shortname] = int(numstr)
                    self.fullPaths[shortname] = '/etc/init.d/' +  shortname
                elif filename[0] == 'S':
                    # wrzuc go do slownika startu
                    startDict[shortname] = int(numstr)
                    self.fullPaths[shortname] = '/etc/init.d/' +  shortname

    def startEntries(self, i):
        _, startDict = self.files[i]
        return self.__getEntries(startDict)

    def stopEntries(self, i):
        stopDict, _ = self.files[i]
        return self.__getEntries(stopDict)
    
    def __getEntries(self, dictionary):
        ret = []
        keys = dictionary.keys()
        for key in keys:
            ret.append((dictionary[key], key))
        ret.sort()
        return ret
    
    def getFilePath(self, label):
        return self.fullPaths[str(label)]

    def getFileContents(self, label):
        f = open(self.fullPaths[str(label)])
        ret = f.read()
        f.close()
        return ret